package com.example.myocr;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TranslateActivity extends Activity {

	EditText edt_text;
	TextView tv_result;
	Button btn_tran;
	Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		edt_text = (EditText) findViewById(R.id.edt_text);
		tv_result = (TextView) findViewById(R.id.tv_result);
		btn_tran = (Button) findViewById(R.id.btn_tran);
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					TranslateResult result = (TranslateResult) msg.getData()
							.getSerializable("result");

					StringBuilder stringBuilder = new StringBuilder();

					for (int i = 0; i < result.getBasicExplain().getExplains()
							.size(); i++) {
						stringBuilder.append(result.getBasicExplain()
								.getExplains().get(i)
								+ ";");
						String resultString = result.getQueryString() + "  "
								+ result.getTranslation() + "   "
								+ stringBuilder;

						tv_result.setText(resultString);

						tv_result.invalidate();
						break;
					}
				}
			};
		};
		btn_tran.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (!edt_text.getText().toString().equals("")) {
					new Thread(new MyRunnable()).start();
				} else {
					Toast.makeText(TranslateActivity.this, "请输入待翻译的文本",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.translate, menu);
		return true;
	}

	class MyRunnable implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				TranslateResult result = TranslateUtil.translateQuery("json",
						edt_text.getText().toString());
				Message message = new Message();
				message.what = 1;
				Bundle bundle = new Bundle();
				// bundle.putString("resultString", resultString);
				bundle.putSerializable("result", result);
				message.setData(bundle);

				handler.sendMessage(message);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}
